package com.lagou.config;

import com.lagou.io.Resources;
import com.lagou.pojo.Configuratioin;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import sun.security.krb5.Config;

import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

/**
 * @Description: 解析xml
 * @Author: yw
 * @Date: 2021/7/23 22:55
 **/
public class XMLConfigBuilder {

    private Configuratioin configuratioin;

    public XMLConfigBuilder() {
        this.configuratioin = new Configuratioin();
    }

    /**
     * 此方法就是将xml配置解析出来
     */
    public Configuratioin parseConfig(InputStream inputStream) throws Exception {
        Document document = new SAXReader().read(inputStream);
        //获取根目录
        Element rootElement = document.getRootElement();
        List<Element> list = rootElement.selectNodes("//property");
        //将所有的信息放入properties集合中
        Properties properties = new Properties();
        for(Element element:list){
            String name = element.attributeValue("name");
            String value = element.attributeValue("value");
            properties.setProperty(name,value);
        }
        //创建连接池
        ComboPooledDataSource comboPooledDataSource =new ComboPooledDataSource();
        comboPooledDataSource.setDriverClass(properties.getProperty("driverClass"));
        comboPooledDataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
        comboPooledDataSource.setUser(properties.getProperty("username"));
        comboPooledDataSource.setPassword(properties.getProperty("password"));
        configuratioin.setDataSource(comboPooledDataSource);

        //mapper.xml解析
        List<Element> list1 = rootElement.selectNodes("//mapper");
        for(Element element :list1){
            //拿到每一个文件地址
            String resource = element.attributeValue("resource");
            InputStream resourceAsStream = Resources.getResourceAsStream(resource);
            XMLMpperBuilder xmlMpperBuilder = new XMLMpperBuilder(configuratioin);

            xmlMpperBuilder.parseMapper(resourceAsStream);

        }
        return configuratioin;
    }
}
